package pannel.recipe;

import system.BasePage;
import pannel.user.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.time.format.DateTimeFormatter;

public class CommentManagementPage extends BasePage {
    private DefaultTableModel model;
    private List<Comment> commentList = new ArrayList<>();
    private JTable table;
    private JTextField searchField;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private CommentDao commentDao;
    private int totalRecords = 0;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public CommentManagementPage(User user) {
        super(user);
        this.commentDao = new CommentDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("评论管理");
        setupContent();
        refreshTable();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("评论内容："));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolBar.setBackground(Color.WHITE);

        JButton deleteButton = new JButton("删除评论");

        toolBar.add(deleteButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(toolBar, BorderLayout.CENTER);

        // 表格设置
        String[] columnNames = {"ID", "菜谱", "用户", "评论内容", "创建时间"};
        model = new DefaultTableModel(new Object[0][], columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.setRowHeight(25);

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件处理
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshTable();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshTable();
            }
        });

        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshTable();
        });

        // 删除评论按钮事件
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int id = (int) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(
                        this,
                        "确定要删除这条评论吗？",
                        "删除确认",
                        JOptionPane.YES_NO_OPTION);

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        if (commentDao.deleteById(id)) {
                            JOptionPane.showMessageDialog(this, "删除成功！");
                            refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "删除失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的评论");
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                String searchText = searchField.getText().trim();
                commentList = commentDao.pageQuery(searchText, currentPage, pageSize);
                totalRecords = commentDao.getTotalCount(searchText);

                model.setRowCount(0);
                for (Comment comment : commentList) {
                    model.addRow(new Object[]{
                            comment.getId(),
                            comment.getRecipeName(),
                            comment.getUsername(),
                            comment.getContent(),
                            comment.getCreateTime().format(DATE_FORMATTER)
                    });
                }
                updatePageInfo();
                table.repaint();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取评论数据失败：" + e.getMessage());
            }
        });
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }
} 